# +----------------------------------------------------------------------
# | ChatWork智能聊天办公系统
# +----------------------------------------------------------------------
# | 软件声明: 本系统并非自由软件,未经授权任何形式的商业使用均属非法。
# | 版权保护: 任何企业和个人不允许对程序代码以任何形式任何目的复制/分发。
# | 授权要求: 如有商业使用需求,请务必先与版权所有者取得联系并获得正式授权。
# +----------------------------------------------------------------------
# | Author: ChatWork Team <2474369941@qq.com>
# +----------------------------------------------------------------------
import time
from tortoise.queryset import Q
from common.utils.urls import UrlUtil
from common.enums.notice import NoticeEnum
from common.models.users import UserModel
from common.models.public import SquareCategoryModel
from common.models.agents import AgentRobotModel
from common.models.agents import AgentSquareModel
from plugins.msg.driver import MsgDriver
from apps.admin.schemas.square import robot_schema as schema


class SquareRobotService:

    @classmethod
    async def lists(cls, params: schema.SquareRobotSearchIn):
        where = AgentSquareModel.build_search({
            "=": ["is_enable", "audit_status", "cate_id"],
            "datetime": ["start_time|end_time@create_time"]
        }, params.__dict__)

        where.append(Q(is_delete=0))
        if params.robot:
            condition = [Q(name__icontains=params.robot)]
            robots = await AgentRobotModel.filter(is_delete=0).filter(*condition).limit(500).values("id")
            ids = [int(item["id"]) for item in robots] or [0]
            where.append(Q(robot_id__in=ids))

        if params.user:
            condition = [Q(sn=params.user)]
            users = await UserModel.filter(*condition).filter(is_delete=0).limit(500).values("id")
            ids = [int(item["id"]) for item in users] or [0]
            where.append(Q(user_id__in=ids))

        _model = AgentSquareModel.filter(*where).order_by("-id")
        _pager = await AgentSquareModel.paginate(
            model=_model,
            page_no=params.page_no,
            page_size=params.page_size,
            fields=AgentSquareModel.without_field("is_delete,delete_time")
        )

        # 查询分类
        cate_ids = [item["cate_id"] for item in _pager.lists]
        category = await SquareCategoryModel.queryCateDictsById(cate_ids)

        # 查智能体
        robot_ids = [item["robot_id"] for item in _pager.lists]
        robots = await AgentRobotModel.queryRobotDictsById(robot_ids)

        # 查询用户
        user_ids = [item["user_id"] for item in _pager.lists]
        users = await UserModel.queryUserDictsById(user_ids)

        _lists = []
        for item in _pager.lists:
            robot = robots.get(item["robot_id"]) or {}
            user = users.get(item["user_id"]) or {}
            cate = category.get(item["cate_id"]) or {}

            _lists.append(schema.SquareRobotListVo(
                id=item["id"],
                cate_id=item["cate_id"],
                robot_code=robot.get("code", ""),
                robot_name=robot.get("name", ""),
                robot_logo=await UrlUtil.to_absolute_url(robot.get("logo", "")),
                category=cate.get("name", "-"),
                sort=item["sort"],
                audit_result=item["audit_result"],
                audit_status=item["audit_status"],
                is_enable=item["is_enable"],
                create_time=item["create_time"],
                update_time=item["update_time"],
                user={
                    "sn": user.get("sn", "").strip(),
                    "nickname": user.get("nickname", ""),
                    "mobile": user.get("mobile", ""),
                    "avatar": await UrlUtil.to_absolute_url(user.get("avatar", ""))
                }
            ))

        _pager.lists = _lists
        return _pager

    @classmethod
    async def audit(cls, post: schema.SquareRobotAuditIn):
        await AgentSquareModel.filter(id=post.id).filter(is_delete=0).get()
        await AgentSquareModel.filter(id=post.id).update(
            audit_result=post.audit_result,
            audit_status=post.audit_status,
            update_time=int(time.time())
        )

    @classmethod
    async def edit(cls, post: schema.SquareRobotEditIn):
        await AgentSquareModel.filter(id=post.id).filter(is_delete=0).get()
        await AgentSquareModel.filter(id=post.id).update(
            cate_id=post.cate_id,
            sort=post.sort,
            is_enable=post.is_enable,
            update_time=int(time.time())
        )

    @classmethod
    async def delete(cls, id_: int, reason: str):
        record = await AgentSquareModel.filter(id=id_, is_delete=0).get()
        await AgentSquareModel.filter(id=id_).update(
            is_delete=0,
            delete_time=int(time.time())
        )

        # 查询智能体
        robot = await AgentRobotModel.filter(id=record.id).first()

        # 发送用户通知
        await MsgDriver.send(scene=NoticeEnum.SQUARE_ROBOT_DELETE, params={
            "user_id": record.user_id,
            "code": robot.code,
            "name": robot.name,
            "reason": reason
        })

    @classmethod
    async def disable(cls, id_: int, reason: str):
        """
        视频广场禁显。

        Args:
            id_ (int): 广场ID。
            reason (str): 原因信息。

        Author:
            zero
        """
        # 查找记录
        record = await AgentSquareModel.filter(id=int(id_), is_delete=0).get()

        # 调整状态值
        status = 0 if record.is_enable else 1
        await AgentSquareModel.filter(id=id_, is_delete=0).update(
            is_enable=status,
            update_time=int(time.time())
        )

        # 查询智能体
        robot = await AgentRobotModel.filter(id=record.id).first()

        # 发送用户通知
        scene = NoticeEnum.SQUARE_ROBOT_SHOW if status == 1 else NoticeEnum.SQUARE_ROBOT_HIDDEN
        await MsgDriver.send(scene=scene, params={
            "user_id": record.user_id,
            "code": robot.code,
            "name": robot.name,
            "reason": reason or "-"
        })
